package com.example.user.myfirstapp.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.view.ViewGroup.LayoutParams;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.user.myfirstapp.MainActivity;
import com.example.user.myfirstapp.MyApplication;
import com.example.user.myfirstapp.R;
import com.example.user.myfirstapp.activity.NewsActivity;
import com.example.user.myfirstapp.activity.NewsInfoActivity;
import com.example.user.myfirstapp.activity.SearchActivity;
import com.example.user.myfirstapp.common.Constant;
import com.example.user.myfirstapp.common.StringHelper;
import com.example.user.myfirstapp.entity.NewsInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;

import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.ScrollView;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by user on 2016/5/18.
 */
public class HomeFragment extends Fragment implements View.OnClickListener{
    private Intent intent;
    private View view;
    private Button bt_search;
    private ViewPager viewPager;
    private MainActivity mainActivity;
    private LinearLayout ll_topnews;
    private Gson gson;
    /**
     * 装点点的ImageView数组
     */
    private ImageView[] tips;
    /**
     * 装ImageView数组
     */
    private ImageView[] mImageViews;
    /**
     * 图片资源id
     */
    private int[] imgIdArray;
    private int imgIdArrayLength;
    private ViewGroup group;
    //当前图片的索引号,设置为长度200，这样子开始就能往左滑动
    private int currposition=200;
    private LinearLayout ll_home_top;
    private PullToRefreshScrollView pull_refresh_scrollview;
    private Boolean isDown;
    private TextSwitcher textSwitcher_tag,textSwitcher_title;

    //新闻滚动
    private List<NewsInfo> newsLists;
    private int newsListStart=0;
    private int curNewsListPostion=0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        initView();
        return view;
    }

    //初始化
    private void initView(){
        view = View.inflate(getActivity(), R.layout.flg_home, null);
        mainActivity =(MainActivity) getActivity();

        bt_search=(Button)view.findViewById(R.id.bt_search);
        bt_search.setOnClickListener(this);

        //跳转到新闻页
        ll_topnews=(LinearLayout) view.findViewById(R.id.ll_topnews);
        ll_topnews.setOnClickListener(this);

        ll_home_top=(LinearLayout)view.findViewById(R.id.ll_home_top);
        group = (ViewGroup)view.findViewById(R.id.viewGroup);
        viewPager = (ViewPager) view.findViewById(R.id.viewPager);
        //设置viewPager滑动不受SlidingMenu的影响
        mainActivity.slideMenu.addIgnoredView(viewPager);
        //图片滚动
        imagesBanner();

        //下拉刷新
        pullRefresh();

        //新闻滚动
        newsRoll();

        //打开左侧滑动菜单按钮
        Button bt_openSlideMenu=(Button) view.findViewById(R.id.bt_openSlideMenu);
        bt_openSlideMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!mainActivity.slideMenu.isMenuShowing()) {
                    mainActivity.slideMenu.toggle();
                }
            }
        });


    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_topnews:
                Intent intent = new Intent(getActivity(), NewsActivity.class);
                startActivity(intent);
                //从右往左切换
                getActivity().overridePendingTransition(R.animator.slide_right_in,0);
                break;
            case R.id.bt_search:
                intent =new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /***********************************************************************************************
    * 图片滚动
    * */
    private void imagesBanner(){
        //载入图片资源ID
        imgIdArray = new int[]{R.mipmap.ectouch2_ad1, R.mipmap.ectouch2_ad2,R.mipmap.ectouch2_ad3, R.mipmap.ectouch2_ad2};
        imgIdArrayLength= imgIdArray.length;
        if(imgIdArrayLength>0) {
            //将点点加入到ViewGroup中
            tips = new ImageView[imgIdArrayLength];
            int tipLength=tips.length;
            for (int i = 0; i < tipLength; i++) {
                ImageView imageView = new ImageView(getActivity());
                imageView.setLayoutParams(new LayoutParams(10, 10));
                tips[i] = imageView;
                if (i == 0) {
                    tips[i].setBackgroundResource(R.mipmap.page_indicator_focused);
                } else {
                    tips[i].setBackgroundResource(R.mipmap.page_indicator_unfocused);
                }
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT));
                layoutParams.leftMargin = 5;
                layoutParams.rightMargin = 5;
                group.addView(imageView, layoutParams);
            }

            //将图片装载到数组中
            int mImageViewsLength=0;
            //如果是1张图片
            if (imgIdArrayLength == 1) {
                mImageViews = new ImageView[2];
                mImageViewsLength=mImageViews.length;
                for (int i = 0; i < mImageViewsLength; i++) {
                    ImageView imageView = new ImageView(getActivity());
                    mImageViews[i] = imageView;
                    imageView.setBackgroundResource(imgIdArray[0]);
                }
                group.setVisibility(View.GONE);
                viewPager.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View arg0, MotionEvent arg1) {
                        // TODO Auto-generated method stub
                        return true;
                    }
                });
            }
            //如果是2张或3张图片
            else if (imgIdArrayLength == 2 || imgIdArrayLength == 3) {
                mImageViews = new ImageView[imgIdArrayLength * 2];
                mImageViewsLength=mImageViews.length;
                for (int i = 0; i < mImageViewsLength; i++) {
                    ImageView imageView = new ImageView(getActivity());
                    mImageViews[i] = imageView;
                    imageView.setBackgroundResource(imgIdArray[(i > (imgIdArrayLength-1)) ? i -imgIdArrayLength : i]);
                }
            }
            else {
                mImageViews = new ImageView[imgIdArrayLength];
                mImageViewsLength=mImageViews.length;
                for (int i = 0; i < mImageViewsLength; i++) {
                    ImageView imageView = new ImageView(getActivity());
                    mImageViews[i] = imageView;
                    imageView.setBackgroundResource(imgIdArray[i]);
                }
            }

            //设置Adapter
            viewPager.setAdapter(new MyAdapter());
            //设置监听，主要是设置点点的背景
            viewPager.setOnPageChangeListener(new OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                }
                @Override
                public void onPageSelected(int position) {
                    currposition=position;
                    setImageBackground(position % imgIdArrayLength);
                }
                @Override
                public void onPageScrollStateChanged(int state) {
                }
            });
            viewPager.setCurrentItem(currposition);
            mHandler.postDelayed(mRunnable, 4000);
        }
    }
    private Handler mHandler =  new Handler();
    private Runnable mRunnable = new Runnable() {
        public void run() {
            //每隔多长时间执行一次
            mHandler.postDelayed(mRunnable, 4000);
            currposition++;
            viewHandler.sendEmptyMessage(currposition);
        }
    };
    private final Handler viewHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            viewPager.setCurrentItem(msg.what);
            super.handleMessage(msg);
        }
    };

    public class MyAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }
        // 来判断显示的是否是同一张图片，这里我们将两个参数相比较返回即可
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }
        /**
         * PagerAdapter只缓存三张要显示的图片，如果滑动的图片超出了缓存的范围，就会调用这个方法，将图片销毁
         */
        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager)container).removeView(mImageViews[position % mImageViews.length]);
        }
        /**
         * 载入图片进去，用当前的position 除以 图片数组长度取余数是关键
         */
        @Override
        public Object instantiateItem(View container, int position) {
            try {
                ((ViewPager)container).addView(mImageViews[position % mImageViews.length], 0);
            }catch(Exception e){
                //handler something
            }
            return mImageViews[position % mImageViews.length];
        }
    }

    /**
     * 设置选中的tip的背景
     * @param selectItems
     */
    private void setImageBackground(int selectItems){
        for(int i=0; i<tips.length; i++){
            if(i == selectItems){
                tips[i].setBackgroundResource(R.mipmap.page_indicator_focused);
            }else{
                tips[i].setBackgroundResource(R.mipmap.page_indicator_unfocused);
            }
        }
    }
    /***********************************************************************************************
     * 图片滚动结束
     * */

    //下拉刷新
    private void pullRefresh(){
        pull_refresh_scrollview=(PullToRefreshScrollView)view.findViewById(R.id.pull_refresh_scrollview);
        pull_refresh_scrollview.setMode(PullToRefreshBase.Mode.BOTH);
        ILoadingLayout startLabels = pull_refresh_scrollview.getLoadingLayoutProxy(true,false);
        ILoadingLayout endLabels = pull_refresh_scrollview.getLoadingLayoutProxy(false,true);
        startLabels.setPullLabel(getString(R.string.startPullLabel));
        startLabels.setRefreshingLabel(getString(R.string.refreshingLabel));
        startLabels.setReleaseLabel(getString(R.string.releaseLabel));
        endLabels.setPullLabel(getString(R.string.endPullLabel));
        endLabels.setRefreshingLabel(getString(R.string.refreshingLabel));
        endLabels.setReleaseLabel(getString(R.string.releaseLabel));
        pull_refresh_scrollview.setOnPullEventListener(new PullToRefreshBase.OnPullEventListener<ScrollView>() {
            @Override
            public void onPullEvent(PullToRefreshBase<ScrollView> refreshView, PullToRefreshBase.State state, PullToRefreshBase.Mode direction) {
                switch (direction){
                    case PULL_FROM_START://下拉
                        isDown=true;
                        break;
                    case PULL_FROM_END://上拉
                        isDown=false;
                        break;
                    default:
                        break;
                }
            }
        });
        pull_refresh_scrollview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //执行刷新函数
                new GetDataTask().execute();
            }

            class GetDataTask extends AsyncTask<Void, Void, String[]> {
                @Override
                protected String[] doInBackground(Void... params) {
                    // Simulates a background job.
                    try {
                        if(!isDown) {
                            Thread.sleep(2000);
                        }

                    } catch (Exception e) {
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String[] result) {
                    super.onPostExecute(result);
                    // Do some stuff here

                    // Call onRefreshComplete when the list has been refreshed.

                    pull_refresh_scrollview.onRefreshComplete();


                }
            }
        });
    }

    /***********************************************************************************************
     * 新闻滚动开始
     * */
    private void newsRoll(){
        String url = "http://"+ Constant.host+":"+Constant.port+"/api/NewsInfo/GetTopNews/";
        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        setTextSwitcher(result);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getActivity(), "网络请求失败",
                                Toast.LENGTH_LONG).show();
                    }
                });
        request.setTag("getNewsList");
        MyApplication.getHttpQueue().add(request);
    }
    private void setTextSwitcher(String json){
        gson = new Gson();
        newsLists=new ArrayList<NewsInfo>();
        newsLists = gson.fromJson(json, new TypeToken<List<NewsInfo>>(){}.getType());
        if(newsLists!=null&&newsLists.size()>0) {
            textSwitcher_tag= (TextSwitcher) view.findViewById(R.id.textSwitcher_tag);
            textSwitcher_title= (TextSwitcher) view.findViewById(R.id.textSwitcher_title);
            textSwitcher_title.setFactory(new ViewSwitcher.ViewFactory() {
                @Override
                public View makeView() {
                    final TextView tv = new TextView(getActivity());
                    //tv.setTextColor(Color.BLACK);
                    return tv;
                }
            });
            textSwitcher_title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int p=curNewsListPostion;
                    NewsInfo news = newsLists.get(p);
                    goToNewInfo(news);
                }
            });
            textSwitcher_tag.setFactory(new ViewSwitcher.ViewFactory() {
                @Override
                public View makeView() {
                    final TextView tv = new TextView(getActivity());
                    tv.setTextColor(Color.RED);
                    tv.setPadding(5, 1, 5,1);
                    tv.setTextSize(12);
                    tv.setBackgroundResource(R.drawable.rounded_border_red);
                    return tv;
                }
            });
            textSwitcher_tag.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int p=curNewsListPostion;
                    NewsInfo news = newsLists.get(p);
                    goToNewInfo(news);
                }
            });

            final Handler newsRollhandler = new Handler();
            newsRollhandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    int len=newsLists.size();
                    curNewsListPostion=newsListStart++ % len;
                    NewsInfo news=newsLists.get(curNewsListPostion);
                    textSwitcher_tag.setText(news.getNewsTypeName());
                    textSwitcher_title.setText(StringHelper.cutString(news.getNewsName(),15));
                    newsRollhandler.postDelayed(this, 2000);
                }
            }, 2000);
        }
    }
    private void goToNewInfo(NewsInfo news){
        //传递news对象
        intent =new Intent(getActivity(),NewsInfoActivity.class);
        Bundle bundle=new Bundle();
        bundle.putSerializable("news", news);
        intent.putExtras(bundle);
        startActivity(intent);
        //从右往左切换
        getActivity().overridePendingTransition(R.animator.slide_right_in,0);
    }
    /***********************************************************************************************
     * 新闻滚动结束
     * */

    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeCallbacks(mRunnable);
        //结束时队列里面注销
        MyApplication.getHttpQueue().cancelAll("getNewsList");
    }
}
